package com.ahwei.common.sentinel.handler;

import com.ahwei.common.rest.base.R;
import com.ahwei.common.rest.util.ResponseUtils;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * sentinel统一降级限流策略。
 * </p>
 *
 * @author ahWei
 * @email：ahwei163@qq.com
 * @since 2022-06-06 14:04:42
 */
@Slf4j
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {
    @Autowired
    private ResponseUtils responseUtils;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.error("sentinel降级，资源名称{}", e.getRule().getResource(), e);
        // 太多请求 429
        responseUtils.outWriter(R.error("请求过多!"),HttpStatus.TOO_MANY_REQUESTS.value(),response);
    }
}